from docx import Document
import re

# Load the original document
doc = Document('/Users/wanghao4799/Documents/# Code_Studio/Markdown_Script/MiandianEarthquake/V2.0/【V2.1】缅甸7.9级地震震后应急响应与灾后协同救援机制研究.docx')

# Regex to find citations in text [number]
citation_pattern = re.compile(r'\[(\d+)\]')

# Track order of first appearance
old_to_new = {}
new_order = []

# First pass: scan body text to record citations in order
for para in doc.paragraphs:
    for match in citation_pattern.finditer(para.text):
        old_num = match.group(1)
        if old_num not in old_to_new:
            new_order.append(old_num)
            old_to_new[old_num] = str(len(new_order))

# Identify reference list start index
ref_start_idx = None
for i, para in enumerate(doc.paragraphs):
    if para.text.strip().startswith('[') and ']' in para.text:
        ref_start_idx = i
        break

# Extract references
references = []
if ref_start_idx is not None:
    for para in doc.paragraphs[ref_start_idx:]:
        text = para.text.strip()
        m = citation_pattern.match(text)
        if m:
            old_num = m.group(1)
            ref_text = text[len(m.group(0)):].strip()
            references.append((old_num, ref_text))

# Assign new numbers to references not cited
for old_num, _ in references:
    if old_num not in old_to_new:
        new_order.append(old_num)
        old_to_new[old_num] = str(len(new_order))

# Second pass: replace citations in text
for para in doc.paragraphs:
    for run in para.runs:
        text = run.text
        new_text = citation_pattern.sub(lambda m: f'[{old_to_new[m.group(1)]}]', text)
        if new_text != text:
            run.text = new_text

# Remove old reference paragraphs
if ref_start_idx is not None:
    for _ in range(len(doc.paragraphs) - ref_start_idx):
        p = doc.paragraphs[ref_start_idx]._element
        p.getparent().remove(p)

    # Add sorted references by new order
    for old_num in new_order:
        # find ref_text
        ref_text = next((rt for o, rt in references if o == old_num), None)
        if ref_text:
            new_num = old_to_new[old_num]
            doc.add_paragraph(f'[{new_num}] {ref_text}')

# Save the new document
output_path = '/Users/wanghao4799/Documents/output.docx'
doc.save(output_path)

output_path
